#!/usr/bin/env python
# coding:utf8
"""
作者:pawn
邮箱:pawn9537@gmail.com
日期:18-1-3
时间:下午8:18
"""
import enum
import time
import typing
from logging import getLogger
import requests
import urllib3
from pandas import read_json

from itick_api.exceptions import ItickException

log = getLogger(__name__)

urllib3.disable_warnings()

DEBUG_CODE = ["CNSHAQ"]


class DataFrame(enum.Enum):
    json = "Json"
    data_frame = "DataFrame"


class ProductType(enum.Enum):
    stock = "股票"
    fund = "基金"
    index = "指数"
    futures = "期货"
    option = "期权"

    @classmethod
    def get_choices(cls):
        return {i.value: i.name for i in cls}

    @classmethod
    def get_name_set(cls):
        return {i.name for i in cls}

    @classmethod
    def get_value_set(cls):
        return {i.value for i in cls}

    @classmethod
    def get_mapping_value(cls, value):
        if value not in cls.get_value_set():
            raise ItickException(None, f"Unsupported product type {value}")
        return cls.get_choices().get(value)


class ItickAPI:
    @property
    def itick_key(self):
        return self._itick_key

    @property
    def product_type(self):
        return self._product_type

    def __init__(
            self,
            itick_key,
            product_type,
            product_code,
            call_back_function=None,
            item_code: typing.List[str] = [],
            debug=False
    ):
        self._itick_key = itick_key
        self._product_type = ProductType.get_mapping_value(product_type)
        self._product_code = product_code
        self.s = requests.Session()
        self.call_back_function = call_back_function
        self._item_code = item_code
        if debug and product_code not in DEBUG_CODE:
            raise ItickException(None, f"Unsupported product code {product_code} in the debug")

        self._gateway = f"https://itick.cn/{self._product_type}/{self._itick_key}/{self._product_code}"

    def get_all_market_url(self):
        return self._gateway

    def get_item_url(self):
        str_item_code = ",".join(self._item_code)
        return f"{self._gateway}/{str_item_code}"

    def get_tick_data(self, request_url):
        try:
            response = self.s.get(request_url, verify=False)
        except Exception as e:
            raise ItickException(None, e)
        if response.status_code == 200:
            return response.text
        elif response.status_code == 503:
            pass
        else:
            raise ItickException(response.status_code, None)

    def call_back(self, data_format):
        if not self.call_back_function:
            raise ItickException(None, f"Unsupported notify url {self.call_back_function}")
        requests_url = self.get_all_market_url()
        if self._item_code:
            requests_url = self.get_item_url()
        while True:
            time.sleep(1)
            data = self.get_tick_data(requests_url)
            if not data:
                continue
            if data_format == "DataFrame":
                data = read_json(data)
                self.call_back_function(data)
            self.call_back_function(data)


if __name__ == '__main__':
    def accept_function(data):
        log.warning(data)


    api = ItickAPI(
        itick_key="RPHgnUjLvXk3lKrYVofz2dcwQet8bAxF",
        product_type="股票",
        product_code="CNHKMS",
        # item_code=["159001.SZ"],
        call_back_function=accept_function,
    )
    log.warning(api.get_all_market_url())
    api.call_back(data_format=DataFrame.json.value)
